package event

import (
	"context"
)

var evHandlersMap = make(map[string][]EvHandler)
var mode int

const (
	Pro   = 0
	DEBUG = 1
)

type EvHandler func(ctx context.Context, ev Named) error
type EvHandlerWithEvType[EV Named] func(ctx context.Context, ev EV) error

func AddEventHandler[Ev Named](handler EvHandlerWithEvType[Ev]) {
	var ev Ev

	SetEventNameIfEventNameDefault(ev)
	evName := ev.EventName()
	handlers := evHandlersMap[evName]
	handlers = append(handlers, func(ctx context.Context, ev Named) error {
		return handler(ctx, ev.(Ev))
	})
	evHandlersMap[evName] = handlers
}

func Publish[Ev Named](ctx context.Context, ev Ev) error {
	ctx = context.WithValue(ctx, DBList, new([]CommandHandler))
	handlers := evHandlersMap[ev.EventName()]
	for _, handler := range handlers {
		err := handler(ctx, ev)
		if err != nil {
			return err
		}
	}
	return WriteWithContext(ctx)
}
